"""
文件流处理示例 - 展示Gua框架的文件流处理能力
重构版本：基于Linus设计哲学，消除重复代码
"简单胜过复杂，零内存占用"
"""

import asyncio
import uuid
import time
from gua import GuaApp, respond, stream, file_handler, create_websocket_manager
from gua.streaming_utils import create_file_download_stream
from gua.websocket_utils import create_upload_progress_websocket

app = GuaApp()
ws_manager = create_websocket_manager()

@app.route("/")
async def index():
    """文件流处理首页"""
    return respond("""
    <!DOCTYPE html>
    <html>
        <head>
            <title>文件流处理示例</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
                .section h2 { margin-top: 0; }
                a { color: #2196F3; text-decoration: none; }
                a:hover { text-decoration: underline; }
                form { margin-top: 10px; }
                input[type="file"] { margin-right: 10px; }
                button { padding: 5px 15px; background-color: #2196F3; color: white; border: none; border-radius: 3px; cursor: pointer; }
            </style>
        </head>
        <body>
            <h1>📁 文件流处理示例</h1>
            
            <div class="section">
                <h2>📥 文件下载</h2>
                <p><a href="/download/small">小文件 (1KB)</a></p>
                <p><a href="/download/medium">中等文件 (1MB)</a></p>
                <p><a href="/download/large">大文件 (10MB)</a></p>
            </div>
            
            <div class="section">
                <h2>📤 文件上传</h2>
                <form action="/upload" method="post" enctype="multipart/form-data">
                    <input type="file" name="file" required>
                    <button type="submit">上传</button>
                </form>
            </div>
            
            <div class="section">
                <h2>🔄 流式处理</h2>
                <p><a href="/process">流式数据处理</a></p>
                <p><a href="/convert">文件格式转换</a></p>
            </div>
        </body>
    </html>
    """)


@app.route("/download/small")
async def download_small():
    """下载小文件示例 - 使用流式构建器"""
    content = "这是一个小文件示例\n" * 20
    
    return (
        stream()
        .text(content, 0.01)  # 每个字符延迟0.01秒
        .build(download=True, filename="small_file.txt")  # 设置下载头部
    )


@app.route("/download/medium")
async def download_medium():
    """下载中等文件示例 - Linus式重构：消除重复代码"""
    return create_file_download_stream("medium_file.txt", "medium")


@app.route("/download/large")
async def download_large():
    """下载大文件示例 - Linus式重构：消除重复代码"""
    return create_file_download_stream("large_file.txt", "large")


@app.route("/upload", methods=["POST"])
async def upload_file(request):
    """流式文件上传 - 零内存占用"""
    # 生成唯一文件名
    filename = f"upload_{uuid.uuid4().hex[:8]}_{int(time.time())}.bin"
    
    try:
        # 流式保存文件
        file_info = await file_handler.save_stream(request, filename)
        
        return respond({
            "success": True,
            "message": "文件上传成功",
            "file": file_info,
            "upload_time": time.time()
        })
    except Exception as e:
        return respond({
            "success": False,
            "error": str(e)
        }, status=500)


@app.route("/process")
async def process_stream():
    """流式文件处理示例 - Linus式重构：使用通用流式生成器"""
    from gua.streaming_utils import stream_builder
    
    async def process_data():
        for i in range(100):
            # 模拟数据处理
            data = {
                "index": i,
                "original": f"data_{i}",
                "processed": f"processed_data_{i}_{time.time()}",
                "checksum": hash(f"data_{i}") % 10000
            }
            
            yield f"处理第 {i+1} 条数据: {data}\n"
            await asyncio.sleep(0.05)
    
    return stream_builder.create_simple_stream(
        data_count=100,
        delay=0.05,
        data_prefix="处理",
        headers={
            "content-type": "text/plain",
            "content-disposition": "attachment; filename=processed_data.txt"
        }
    )


@app.route("/convert")
async def convert_stream():
    """文件格式转换示例 - Linus式重构：使用通用流式生成器"""
    from gua.streaming_utils import stream_builder
    
    async def convert_data():
        # 模拟CSV到JSON转换
        yield "开始CSV到JSON转换...\n"
        await asyncio.sleep(0.1)
        
        # CSV头部
        yield "id,name,age,city\n"
        
        # 生成示例数据
        for i in range(50):
            csv_line = f"{i},用户{i},20+i%50,城市{i%10}\n"
            yield csv_line
            
            # 同时生成JSON版本
            json_data = {
                "id": i,
                "name": f"用户{i}",
                "age": 20 + i % 50,
                "city": f"城市{i % 10}"
            }
            
            yield f"JSON: {json_data}\n"
            await asyncio.sleep(0.02)
        
        yield "转换完成！\n"
    
    return stream_builder.create_simple_stream(
        data_count=1,
        delay=0.02,
        data_prefix="转换",
        headers={
            "content-type": "text/plain",
            "content-disposition": "attachment; filename=converted_data.txt"
        }
    )


@app.websocket("/ws")
async def websocket_handler(scope, receive, send):
    """WebSocket处理器 - 文件上传进度 - Linus式重构：使用通用WebSocket处理器"""
    return await create_upload_progress_websocket(scope, receive, send)


if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.file_streaming:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.file_streaming:app --example-info")